#coding=utf-8

import requests
import json
import env_config
from app.models import DataDetail
import uuid
import socket
from app.lib.RedisPool import redisConn
from app.utils.util import str_random,int_timestamp,calcCrfuid

from app.lib import MysqlPool

def white(user):
    result = False
    if user.whitelist_system == '循环贷':
        result = white_xhd(user)
    elif user.whitelist_system == '轻生活贷':
        result = white_qshd(user)
    elif user.whitelist_system == '分期商城':
        result = white_icmall(user)
    elif user.whitelist_system == '融360':
        result = white_r360(user)
    if user.crfuid:
        user.extra['db_prefix'] =calcCrfuid(user.crfuid)
    return result
def  white_xhd(user):
    data = {
        'channel':'open',
        'user_phone':user.phone,
        'user_idno':user.idno,
        'user_name':user.name,
        'alipay_expenditure':'1000',
        'month_count':'5',
        'mark':'0.1',
        'is_confirm':'1',
        'product_type':'1',
        'flow_id':'F030'
    }
    result = requests.post(url=env_config.ENV_LIST.get(user.env).get('url_crm')+'/crf_crm/xhd/apply.do',data = json.dumps(data),headers = {'Content-Type':'application/json;charset=utf-8'})
    print(result.status_code)
    if result.status_code != 200:
        user.is_whitelist = False
        return False
    res_json = result.json()
    user.crfuid = res_json.get('crfuid')
    if user.crfuid is None:
        user.is_whitelist = False
        return False
    return True

def  white_r360(user):
    data = {
        'channel':'',
        'auditCode':1,
        'userPhone':user.phone,
        'userIdNo':user.idno,
        'userName':user.name,
        'applyScore':'450',
        'address':u'户籍地址自动化工具生成',
        'postalAddress':u'邮寄地址自动化工具生成',
        'signOrg':u'机关自动化工具生成',
        'unitName':u'单位名称自动化工具生成',
        'industryCode':u'1',
        'industryName':u'农. 林. 牧. 渔业',
        'incomeStart':u'0',
        'incomeEnd':u'1999',
        'alipayCheckStatus':1,
        'osType':1,
        'jdCheckStatus':0,
        'antCreditPayAmount':1300,
        'jdIousAmount':1300,
        'idCardImgHead':'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRrOAaIVAAALSakA3u4A555.jpg?token=d8c583e4c717005d060df5e2cff9b3b3&ts=1521013741',
        'idCardImgTail':'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRqCAMcpfAALdzn-1hkA831.jpg?token=40c655f7cfebf81f30220de3072073a5&ts=1521013723'
    }
    result = requests.post(url=env_config.ENV_LIST.get(user.env).get('url_crm')+'/crf_crm/rong/applyWhite.do',data = json.dumps(data),headers = {'Content-Type':'application/json;charset=utf-8'})
    if result.status_code != 200:
        user.is_whitelist = False
        return False
    res_json = result.json()
    user.crfuid = res_json.get('crfUid')
    if user.crfuid is None:
        user.is_whitelist = False
        return False
    return True
def  white_icmall(user):
    if user.kissoid is None:
        user.is_whitelist = False
        user.describe = u'kissoid为空，无法注册轻生活贷白名单，请确保已勾选注册选项 和 注册成功'
        return False
    data = {
        'faceContrastStatus':1,
        'kissoId':user.kissoid,
        'userPhone':user.phone,
        'userIdNo':user.idno,
        'userName':user.name,
        'applyScore':450,
        'address':u'户籍地址自动化工具生成',
        'homeAddress':u'家庭地址自动化工具生成',
        'signOrg':u'机关自动化工具生成',
        'unitName':u'单位名称自动化工具生成',
        'industryCode':u'1',
        'industryName':u'农. 林. 牧. 渔业',
        'incomeStart':u'0',
        'incomeEnd':u'1999',
        'alipayTransactionCnt':20,
        'alipayTransactionAmount':600,
        'alipayTaobaoAmount':4000,
        'alipayCheckStatus':1,
        'isConfirm':1,
        'osType':1,
        'antCreditPayAmount':2400,
        'email':'123456@qq.com',
        'idCardImgHead':'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRrOAaIVAAALSakA3u4A555.jpg?token=d8c583e4c717005d060df5e2cff9b3b3&ts=1521013741',
        'idCardImgTail':'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRqCAMcpfAALdzn-1hkA831.jpg?token=40c655f7cfebf81f30220de3072073a5&ts=1521013723'
    }
    result = requests.post(url=env_config.ENV_LIST.get(user.env).get('url_crm')+'/crf_crm/icmall/applyWhite.do',data = json.dumps(data),headers = {'Content-Type':'application/json;charset=utf-8'})
    if result.status_code != 200:
        user.is_whitelist = False
        return False
    res_json = result.json()
    user.crfuid = res_json.get('crfUid')
    if user.crfuid is None:
        user.is_whitelist = False
        return False
    return True
def  white_qshd(user):
    if user.kissoid is None:
        user.is_whitelist = False
        user.describe = u'kissoid为空，无法注册轻生活贷白名单，请确保已勾选注册选项 和 注册成功'
        return False
    applyId = str(uuid.uuid1())
    data = {
        'userPhone':user.phone,
        'applyId':applyId,
        'kissoId':user.kissoid,
        'userIdNo': user.idno,
        'userName': user.name,
        'faceContrastStatus': '2',
        'applyScore': '',
        'address': u'户籍地址自动化工具生成',
        'postalAddress':u'邮寄地址自动化工具生成',
        'idCardImgHead': 'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRrOAaIVAAALSakA3u4A555.jpg?token=d8c583e4c717005d060df5e2cff9b3b3&ts=1521013741',
        'idCardImgTail': 'http://pics1-test.crfchina.com/group1/M00/0A/02/CsJQDVqpRqCAMcpfAALdzn-1hkA831.jpg?token=40c655f7cfebf81f30220de3072073a5&ts=1521013723',
        'signOrg': '机关自动化工具生成',
        'unitName': '单位名称自动化工具生成',
        'industryCode': 1,
        'industryName': '农. 林. 牧. 渔业',
        'incomeStart': 0,
        'incomeEnd': 1999

    }
    result = requests.post(url=env_config.ENV_LIST.get(user.env).get('url_crm')+'/crf_crm/qshd/applyWhite.do',data = json.dumps(data),headers = {'Content-Type':'application/json;charset=utf-8'})
    if result.status_code != 200:
        user.is_whitelist = False
        return False
    res_json = result.json()
    user.crfuid = res_json.get('crfUid')
    if user.crfuid is None:
        user.is_whitelist = False
        return False
    return True

def login_auth_server(user):
    data = {
        "password": user.password,
        "account": user.phone
    }
    url = env_config.ENV_LIST.get(user.env).get('url_passport') + '/auth_server/auth/login/' + user.phone
    print('登录： '+url)
    print(json.dumps(data))
    result = requests.post(url=url,
                          data=json.dumps(data), headers={'Content-Type': 'application/json;charset=utf-8',
                                                          'User-Agent': 'CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)'})
    print(result.content.decode('utf-8'))
    try:
        res_json = result.json()
    except UnboundLocalError:
        return False
    except AttributeError:
        return False
    if res_json.get('access_token') is not None:
        user.extra['access_token'] = res_json.get('access_token')
        return True
    return False

def appcore_pagetag(user):
    url = env_config.ENV_LIST.get(user.env).get('url_app') + '/app_core/pageTag'
    print('pagetag： ' + url)
    result = requests.get(url=url,headers={'Authorization': 'Bearer '+user.extra.get('access_token')})
    print(result.content.decode('utf-8'))
    try:
        res_json = result.json()
    except UnboundLocalError:
        return False
    except AttributeError:
        return False
    if res_json.get('kissoId') is not None:
        user.kissoid = res_json.get('kissoId')
        return True
    return False

def register_auth_server(user):
    ip = socket.gethostbyname(socket.gethostname())
    redisconf = env_config.ENV_LIST.get(user.env).get('redis_auth_server')
    r = redisConn(redisconf)
    pipe = r.pipeline()
    token = str_random(32)
    register_sms = {
        "verifyToken":token,
        "status":1,
        "createTime":int_timestamp(),
        "updateTime":int_timestamp(),
        "ip":ip,
        "userAgent":"CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)",
        "resource":{
            "phone":user.phone,
            "intent":"register",
            "sendWay":"0",
            "asyn":False,
            "fromSystem":None,
            "code":"000000"
        },
        "controlType":"register"
    }
    pipe.lpush('control:'+token,json.dumps(register_sms))
    pipe.expire('control:' + token, time=300)
    pipe.execute()
    user.password = '111aaa'
    data = {
        "password":user.password,
        "systemNo":"app_core",
        "fromSystem":"xjd",
        "accountName":user.phone,
        "clientInfo":{
            "androidID":"427063efc62c6ba2",
            "appVersion":"52",
            "blackBox":"",
            "clientId":"190e35f7e065de97f2f",
            "deviceId":"427063efc62c6ba2",
            "gps":"",
            "idfa":"",
            "imei":"864590037706681",
            "latitude":"31.223142",
            "locationAddr":"china",
            "loginChannel":"APP",
            "longitude":"121.359974",
            "mac":"14:5F:94:04:1C:0C",
            "model":"HUAWEI",
            "os":"android7.0",
            "vua":"CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)"
        }
    }
    url = env_config.ENV_LIST.get(user.env).get('url_passport') + '/auth_server/auth/register/'+token
    result = requests.put(url=url,
                           data=json.dumps(data), headers={'Content-Type': 'application/json;charset=utf-8','User-Agent':'CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)'})
    try:
        res_json = result.json()
    except UnboundLocalError:
        return False
    except AttributeError:
        return False
    if res_json.get('access_token') is not None:
        user.extra['access_token'] = res_json.get('access_token')
        getKissoId(user)
        return True
    token = str_random(32)
    register_sms['verifyToken'] = token
    register_sms['ip'] = env_config.AUTHSERVER_GATEWAY_IP
    pipe.lpush('control:' + token, json.dumps(register_sms))
    pipe.expire('control:' + token, time=300)
    pipe.execute()
    url = env_config.ENV_LIST.get(user.env).get('url_passport') + '/auth_server/auth/register/' + token
    result = requests.put(url=url,
                          data=json.dumps(data), headers={'Content-Type': 'application/json;charset=utf-8',
                                                          'User-Agent': 'CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)'})
    try:
        res_json = result.json()
    except UnboundLocalError:
        return False
    except AttributeError:
        return False
    if res_json.get('access_token') is not None:
        user.extra['access_token'] = res_json.get('access_token')
        getKissoId(user)
        return True
    return False

def bindCard(user):
    if login_auth_server(user) == False:
        return False
    if appcore_pagetag(user) == False:
        return False
    print(user.extra.get('access_token'))
    url ='%(host)s/h5_dubbo/fcp/cardInfo/?cardNo=%(cardno)s&kissoId=%(kissoid)s&access_token=%(access_token)s' % \
         {'host':env_config.ENV_LIST.get(user.env).get('url_h5'),'cardno':user.bankno,'kissoid':user.kissoid,'access_token':user.extra.get('access_token')}
    print(url)
    result = requests.get(url)
    try:
        res_json = result.json()
    except UnboundLocalError:
        return False
    except AttributeError:
        return False
    bankcode = res_json.get('bankCode')
    cookies = result.cookies
    data = {
        "applicationSource":"h5",
        "autoDeduct":True,
        "bankCardNo":user.bankno,
        "bankCode":bankcode,
        "businessType":"rcs",
        "cityId":"6530",
        "email":None,
        "idType":"0",
        "mobile":user.phone,
        "requestRefNo":str_random(32),
        "systemNo":"rcs"
    }
    url = '%(host)s/h5_dubbo/fts/borrower_open_account?kissoId=%(kissoid)s' % \
          {'host': env_config.ENV_LIST.get(user.env).get('url_h5'),'kissoid': user.kissoid}
    print(url)
    print(json.dumps(data))
    print(cookies)
    result = requests.put(url=url,cookies=cookies,
                          data=json.dumps(data), headers={'Content-Type': 'application/json;charset=utf-8',
                                                          'User-Agent': 'CRF_app/Android/China_Rapid_Finance_4.0.0(Linux;U;Android4.4.2;OPPOR11Build/NMF26X)'})

    print('绑卡结果：'+ result.content.decode('utf-8'))
    return True




def getKissoId(user):
    dbinfo = env_config.ENV_LIST.get(user.env.upper()).get('kisso')
    dbtool = MysqlPool.MysqlPool(dbinfo.get('db_name'))
    result = dbtool.getOne("select * from %(table_name)s.account where account='%(phone)s' limit 1;" % {'phone': user.phone, 'table_name': dbinfo.get('table_name')})
    if result:
        user.kissoid = result.get('kisso_id')
        return True
    return False




#查询账户信息
def query_auth_server_account(data):
    dbinfo = env_config.ENV_LIST.get(data.get('env_tools')).get('kisso')
    dbtool = MysqlPool.MysqlPool(dbinfo.get('db_name'))
    result = dbtool.getOne(
        "select * from {}.account where account=%s limit 1;".format(dbinfo.get('table_name')),(data.get('phone')))
    if result == False:
        return False
    data['crf_account'] = result
    data['kissoid'] = result.get('kisso_id')
    return True

#查询富有账户信息
def query_account_info(data):
    dbinfo = env_config.ENV_LIST.get(data.get('env_tools')).get('fts2db')
    dbtool = MysqlPool.MysqlPool(dbinfo.get('db_name'))
    result = dbtool.getOne(
        "select * from {}.acc_fuiou_virtual_account_info where crf_uid=%s limit 1;".format(dbinfo.get('table_name')),(data.get('crfuid')))
    if result == False:
        return False
    data['acc_fuiou_virtual_account_info'] = result
    return True

